package com.xinqi.xinqidev.controller;

import com.xinqi.xinqidev.pojo.entity.UserVo;
import com.xinqi.xinqidev.pojo.result.MessageResult;
import com.xinqi.xinqidev.pojo.entity.User;
import com.xinqi.xinqidev.pojo.result.Result;
import com.xinqi.xinqidev.pojo.result.ResultUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("user")
public class UserController {

    /**
     * 登陆
     * @param user 提交的用户数据，包含用户名和密码
     * @param session
     * @return
     */
    @PostMapping("/login")
    public MessageResult login(@RequestBody User user, HttpSession session) {
        MessageResult messageResult = new MessageResult();
        if(user != null && "123".equals(user.getPassword())) {
            messageResult.setFlag(true);
            //将数据存储到session对象中
            session.setAttribute("user",user.getUsername());
            session.setAttribute("userId","1");
        } else {
            messageResult.setFlag(false);
            messageResult.setMessage("登陆失败");
        }
        return messageResult;
    }

    /**
     * 获取用户名
     * @param session
     * @return
     */
    @GetMapping("/getUser")
    public Result getUsername(HttpSession session) {
        return ResultUtil.ok(
                new UserVo()
                        .setUserId(Long.valueOf((String) session.getAttribute("userId")))
                        .setUserName((String) session.getAttribute("user"))
        );
    }
}
